package com.yue.ssa.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yue.ssa.bean.Menu;
import com.yue.ssa.bean.RespBean;
import com.yue.ssa.bean.RoleMenu;
import com.yue.ssa.mapper.RoleMenuMapper;
import com.yue.ssa.service.RoleMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhengyl
 * @description
 * @date 2020-07-31 20:23
 */
@Service
@Transactional
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {
    @Override
    public RespBean assignMenus(String rid, List<Menu> menuList) {
        //删除原先的映射关系
        Map<String, Object> params = new HashMap<>();
        params.put("rid", rid);
        this.removeByMap(params);
        //查询所有父菜单
        List<Menu> parent = this.baseMapper.queryParentMenus();
        List<RoleMenu> roleMenus = new ArrayList<>();
        Set<String> pids = new HashSet<>();
        //子菜单
        for (Menu menu : menuList) {
            if (StringUtils.isBlank(menu.getId())) continue;
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMid(menu.getId());
            roleMenu.setRid(rid);
            roleMenu.setOp(menu.isOp());
            roleMenus.add(roleMenu);
            pids.addAll(parent.stream().filter(m -> menu.getCode().indexOf(m.getCode()) != -1).map(Menu::getId).collect(Collectors.toList()));
        }
        //父菜单
        for (String pid : pids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMid(pid);
            roleMenu.setRid(rid);
            roleMenu.setOp(false);
            roleMenus.add(roleMenu);
        }
        //批量保存
        return RespBean.ok(this.saveBatch(roleMenus));
    }
}
